<template>
    <div class="login">
      <div class="loginForm">
        <div class="form">
          <el-form
            :model="loginForm" status-icon :rules="rules" ref="loginFormRef" label-width="100px" class="login-container" label-position="left" @keyup.enter="submitForm(loginFormRef)">
            <h3 class="login_title">中国东盟在线课程资源管理平台</h3>
            <el-form-item class="item" label="账户名" prop="username">
              <el-input  v-model="loginForm.username" prefix-icon="UserFilled"  autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input  show-password v-model="loginForm.password" prefix-icon="Lock" autocomplete="off" ></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <el-input v-model="loginForm.verifyCode" autocomplete="off" style="width:140px;"  placeholder="请输入验证码"></el-input>
              <el-image :src="codeAction" @click="getCode" v-loading="tokenLoading" style="height:32px;margin-left:10px;">
                <template #placeholder>
                  <el-icon><Refresh/>加载中……</el-icon>
                </template>
                <template #error>
                  <el-icon><Picture/></el-icon>
                </template>
              </el-image>
              <!--          <img :src="imgSrc" style="height:32px;margin-left:10px;"/>-->
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(loginFormRef)" :loading="loadingButton">登陆</el-button>
              <!--          <el-icon><user /></el-icon>
                        <el-icon><user-filled /></el-icon>
                        <el-icon><apple /></el-icon>
                        <edit style="width: 1em; height: 1em; margin-right: 8px;" />-->
              <!--          <el-button type="primary" icon="Edit" circle></el-button>-->
            </el-form-item>
          </el-form>
        </div>
        <img src="../assets/image/loginFormBg.png" alt="">
      </div>
    </div>
</template>
<script lang="ts" setup>
import {
  reactive, ref, getCurrentInstance, computed, onMounted,
} from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
// 导入路由
const router = useRouter();// 创建路由对象
const { proxy } = getCurrentInstance(); // 使用proxy代替ctx，因为ctx只在开发环境有效
const store = useStore();

// const imgSrc = computed(() => `${process.env.BASE_URL}a.jpg`);
// console.log(imgSrc);

// 验证码模块
let token = ''; // 用于验证码的token
let tokenLoading = ref<boolean>(false);// 图片的加载验证码
// 验证码的访问地址
const codeAction = ref<string>();
// 变更验证码
const getCode = async () => {
  tokenLoading.value = true; // 在加载中
  // 加上随机数，让图片的缓存失效，否则验证码图片会不变。后改为base64位格式，此代码留存
  // codeAction.value = `${proxy.$urls.API_URL_BACKSTAGE_VERIFYCODE}?random=${new Date().getMilliseconds()}`;
  const responseData = await new proxy.$Request(proxy.$urls.API_URL_BACKSTAGE_VERIFYCODE, { token }).get();
  tokenLoading.value = false; // 结束加载
  token = responseData.data.token; // 获取token
  codeAction.value = `data:image/png;base64,${responseData.data.img}`; //  接收为base64的图片要在头部加上data:image/png;base64,
};
// 初始化生成验证码
onMounted(async () => {
  await getCode();
});

// 登录表单对象
const loginForm = reactive({
  username: 'vistor',
  password: '123456',
  verifyCode: '',
});
let loadingButton = ref(false); // 登录按钮加载状态

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入账户名', trigger: 'blur' },
    {
      min: 3, max: 20, message: '账户名长度必须在3-20个字符之间', trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      min: 6, max: 12, message: '密码长度必须在6-12个字符之间', trigger: 'blur',
    },
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
});
// 定义登录表单的对象
type FormInstance = InstanceType<typeof ElForm>;// 获取构造函数的返回类型，如果是多个就以联合类型的方式返回
const loginFormRef = ref<FormInstance>();
const submitForm = (formEl: FormInstance | undefined) => { // 当点击登录按钮时
  if (formEl) {
    formEl.validate(async (valid) => {
      if (valid) { // 如果验证通过
        loadingButton.value = true;
        const formObj = { // 封装要传递的表单数据
          username: loginForm.username,
          password: loginForm.password,
          verifyCode: loginForm.verifyCode,
          token,
        };
        // const res = await new proxy.$request(proxy.$urls.API_URL_BACKSTAGE_ADMIN_LOGIN, loginForm).post();
        await new proxy.$Request(proxy.$urls.API_URL_BACKSTAGE_ADMIN_LOGIN, null, { params: formObj }).post()
          .then((resData:any) => { // 操作成功
            loadingButton.value = false;
            if (resData.success) { // 如果登录成功
              // 登录成功提示
              ElMessage.success('登录成功');
              // 保存token
              store.commit('setToken', resData.data.accessToken);
              // sessionStorage.setItem('access_token', resData.data.accessToken);
              router.push('/backstage');
            } else { // 登录失败可能会刷新验证码，但验证码错误不会
              if (resData.data !== '') { // 如果错误并传递了数据，说明有验证码信息
                token = resData.data.token; // 获取token
                codeAction.value = `data:image/png;base64,${resData.data.img}`; //  接收为base64的图片要在头部加上data:image/png;base64,
              }
            }
          })
          .catch((error:any) => { // 登录失败，因为服务端登录失败会返回401的http状态码，所以要手动处理
            loadingButton.value = false;
          });
      }
      return false;
    });
  }
};
</script>
<style scoped>
  .login {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100vw;
    height: 100vh;
    background-image:url(../assets/image/loginBg.png);
    background-position: center;
    background-size: cover;
  }
  .loginForm {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9;
  }
    /*设置表单样式*/
  .loginForm .login-container {
    border-radius: 15px;
    background-clip: padding-box;/*背景绘制在衬距方框内（剪切成衬距方框）。*/
    width: 350px;
    padding: 35px 35px 15px 35px;
    color: #fff;
  }
  ::v-deep  .el-form-item__label{
    color: #fff;
  }
  .el-button {
    width: 140px;
    background-color: rgba(25, 1, 255, 0.5);
    border: 0;
  }
  .loginForm img {
    width: 116%;
    height: 136%;
    position: absolute;
    top: -60px;
    left: -35px;
    z-index: -1;
  }
  .login_title {
    font-size: 22px;
    font-weight: 400;
    letter-spacing: 2px;
    margin: 0px auto 40px auto;
    text-align: center;
    color: #fff;
  }
</style>
